package avicit.bdp.oss.utils.upload.utils.minio;

import avicit.bdp.oss.utils.common.Constants;
import avicit.platform6.core.exception.BusinessException;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间：2020-12-09
 * @类说明：MinioUtil
 * @修改记录：
 * @注意事项：
 * @主要功能：Minio基本操作
 */
public class OssUtil {

  private static final Logger logger = LoggerFactory.getLogger(OssUtil.class);

  /**
   * 上传对象
   *
   * @param minioClient
   * @param bucketName
   * @param objectName
   * @param in
   */
  public static void putObject(
      MinioClient minioClient, String bucketName, String objectName, InputStream in) {
    logger.info("开始上传文件[{}-{}]...", bucketName, objectName);

    try {
      minioClient.putObject(
          PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                  in, in.available(), -1)
              .build());
    } catch (Exception e) {
      String message = String.format("上传文件[%s-%s]失败，errMsg=%s.", bucketName, objectName, e);
      logger.error(message);
      throw new BusinessException(message);
    }

    logger.info("上传文件[{}-{}]成功", bucketName, objectName);
  }

  /**
   * 获取对象元数据
   *
   * @param minioClient
   * @param bucketName
   * @param objectName
   * @return
   */
  public static ObjectStat statObject(
      MinioClient minioClient, String bucketName, String objectName) {
    ObjectStat objectStat;
    try {
      objectStat =
          minioClient.statObject(
              StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
    } catch (Exception e) {
      String message = String.format("获取[%s-%s]对象元数据失败，errMsg=%s.", bucketName, objectName, e);
      logger.error(message);
      throw new BusinessException(message);
    }

    return objectStat;
  }

  /**
   * 构建文件名称
   *
   * @param prefix
   * @param objectName
   * @return
   */
  public static String buildFileName(String prefix, String objectName) {
    StringBuilder sb = new StringBuilder();

    if (prefix == null) {
      sb.append(objectName);
    } else if (prefix.equals(Constants.BLACK)) {
      sb.append(objectName);
    } else {
      sb.append(prefix).append(Constants.SLASH).append(objectName);
    }

    return sb.toString();
  }
}
